package com.printeverywhere.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionContext;
import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.dto.GeneralOptions;
import com.printeverywhere.dto.Items;
import com.printeverywhere.dto.MailingSystem;
import com.printeverywhere.dto.Transactions;
import com.printeverywhere.dto.User;
import com.printeverywhere.util.AdminConstants;
import com.printeverywhere.util.CommonUtil;
import com.printeverywhere.util.DateUtil;
import com.printeverywhere.util.MailHelper;
import com.printeverywhere.util.SessionUtil;

public class BuyItNowAction extends FrontBaseSupport implements ServletRequestAware {

	/**  */
	private static final long serialVersionUID = 1L;

	private HttpServletRequest request;

	private Items item;

	private int bidQuantity;

	public BuyItNowAction() {
		super(false, false);
	}

	public String execute() {
		this.item = (Items) CommonFunctionDelegator.getObjectById("itemId", this.item.getItemId(), Items.class);
		return SUCCESS;
	}

	public String buyMessage() {
		this.item = (Items) CommonFunctionDelegator.getObjectById("itemId", this.item.getItemId(), Items.class);
		GeneralOptions generalOptions = (GeneralOptions) ActionContext.getContext().getApplication().get(AdminConstants.GENERAL_OPTIONS);

		synchronized (this) {
			if(generalOptions.getMaximumAllowedNegativeBalance() > (SessionUtil.getUser(request).getCurrentBalance() - (bidQuantity * item.getStartBid()))) {
				addActionError("You do not have enough balance.");
				return INPUT;
			} else {
				this.item.setSold(this.item.getSold() + bidQuantity);
				CommonFunctionDelegator.generalUpdatebyobj(this.item);

				Transactions transactions = new Transactions();
				transactions.setAmount(bidQuantity * item.getStartBid());
				transactions.setBalance(SessionUtil.getUser(request).getCurrentBalance() - (bidQuantity * item.getStartBid()));
				transactions.setDate(DateUtil.getTodaysDate());
				transactions.setTitle("Purchase item");
				transactions.setUser(SessionUtil.getUser(request));
				CommonFunctionDelegator.generalInsertbyobj(transactions);

				SessionUtil.getUser(request).setCurrentBalance(transactions.getBalance());
				CommonFunctionDelegator.generalUpdatebyobj(SessionUtil.getUser(request));

				try {
					MailingSystem mailingSystem = (MailingSystem) ActionContext.getContext().getApplication().get(AdminConstants.MAILING_OPTIONS);
					MailHelper mailHelper = new MailHelper(mailingSystem.getServerAddress(), mailingSystem.getServerUsername(), mailingSystem.getServerPassword());

					StringBuffer URL = new StringBuffer();
					URL.append(CommonUtil.getLocalBasePath(request));
					URL.append("/mail/winItem.htm?id=").append(item.getItemId()).append("&title=").append(item.getTitle()).append("&qty=").append(bidQuantity).append("&amt=").append(bidQuantity * item.getStartBid()).append("&uname=").append(SessionUtil.getUser(request).getUserId());

					String message = CommonUtil.getURLContent(URL.toString());
					mailHelper.sendMail(mailingSystem.getWinnerConfirmEmailAddress(), SessionUtil.getUser(request).getEmail(), "Item won Confirmation", message);

					URL = new StringBuffer();
					URL.append(CommonUtil.getLocalBasePath(request));
					URL.append("/mail/soldItem.htm?id=").append(item.getItemId()).append("&title=").append(item.getTitle()).append("&qty=").append(bidQuantity).append("&amt=").append(bidQuantity * item.getStartBid()).append("&uname=").append(item.getUserId().getUserId());

					message = CommonUtil.getURLContent(URL.toString());
					mailHelper.sendMail(mailingSystem.getWinnerConfirmEmailAddress(), SessionUtil.getUser(request).getEmail(), "Item sold Confirmation", message);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return SUCCESS;
	}

	public Items getItem() {
		return item;
	}

	public void setItem(Items item) {
		this.item = item;
	}

	public int getBidQuantity() {
		return bidQuantity;
	}

	public void setBidQuantity(int bidQuantity) {
		this.bidQuantity = bidQuantity;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public void validate() {
		synchronized (this) {
			this.item = (Items) CommonFunctionDelegator.getObjectById("itemId", this.item.getItemId(), Items.class);

			if((this.item.getQuantity() - this.item.getSold()) < bidQuantity) {
				addActionError("Quantity required by you is not available...");
			}
		}
	}
}
